//
//  PGNetworkTools.swift
//  PGWeibo
//
//  Created by Apple on 15/11/5.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import AFNetworking

class PGNetworkTools: AFHTTPSessionManager {

    private let appKey = "989487992"
    private let appSecret = "b48ccb49604dba0f0ff944b3a09954fb"
    private let redirect_uri = "http://www.baidu.com"

    static let sharedTools: PGNetworkTools = {
        let tools = PGNetworkTools(baseURL: NSURL(string: "https://api.weibo.com/"))
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
}
// MARK: - OAuth授权
extension PGNetworkTools {
    /// 请求授权码的URL 需要拼接
    var oauthUrl: NSURL {
        //https://api.weibo.com/oauth2/authorize?client_id=989487992&redirect_uri=http://www.baidu.com
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    
    typealias PGRequestCallBack = (result: AnyObject?, error: NSError?) -> ()
    ///根据授权码 获得令牌
    func loadAccessToken(code: String, finished:PGRequestCallBack) {
        let parameters = ["client_id": appKey,
                        "client_secret": appSecret,
                        "grant_type": "authorization_code",
                        "code": code,
                        "redirect_uri": redirect_uri]
        let urlString: String = "oauth2/access_token"
        request(.POST, URLString: urlString, parameters: parameters, finished: finished)
    }
    
    private var tokenDict: [String: AnyObject]? {
        if let token = PGUserAccountViewModel.sharedUerAccountViewModel.accessToken {
            return ["access_token": token]
        }
        return nil
    }
    
    /// 加载用户信息
    func loadUserInfo(uid: Int64, finished: PGRequestCallBack) {
//        let parameters = ["access_token": token, "uid": Int(uid)]
//        //https://api.weibo.com/2/users/show.json
//        request(.GET, URLString: "2/users/show.json", parameters: parameters, finished: finished)
        // 1. 获取 token 字典
        guard var params = tokenDict else {
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        
        // 2. 处理网络参数
        let urlString = "2/users/show.json"
        
        params["uid"] = Int(uid)
        
        request(.GET, URLString: urlString, parameters: params, finished: finished)

    }
    // MARK: - 加载微博信息
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(finished: PGRequestCallBack) {
        //https://api.weibo.com/2/statuses/home_timeline.json
        guard let params = tokenDict else {
            // 如果字典为 nil，通知调用方，token 无效
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        request(.GET, URLString: "2/statuses/home_timeline.json", parameters: params, finished: finished)
    }
}

// MARK: - 封装AFN网络框架
extension PGNetworkTools {

    //请求类型
    enum PGRequestMethod: String {
        case POST = "POST"
        case GET = "GET"
    }
    func request(methodType: PGRequestMethod, URLString: String, parameters: AnyObject?, finished: PGRequestCallBack) {
        
        //成功回调
        let success = { (task: NSURLSessionTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        //失败回调
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finished(result: nil, error: error)
        }
        
        if methodType == PGRequestMethod.GET {
            
            GET(URLString, parameters: parameters, success: success, failure: failure)

        }else{
            
            POST(URLString, parameters: parameters, success: success, failure: failure)
            
        }
    }
}
